/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.orderView.dish;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.CardComponentListener;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TConfig;
import com.ruipengkj.bean.TExePos;
import com.ruipengkj.bean.TOrder;
import com.ruipengkj.bean.TUser;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.jna.QueryMember;
import com.ruipengkj.commons.util.print.CashboxPrint;
import com.ruipengkj.commons.util.print.TicketPrint;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.JPanelGridLayoutComponent;
import com.ruipengkj.component.RPJButtonOrderDispose;
import com.ruipengkj.component.jpanel.RPJPanelOrderDispose;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.service.TConfigService;
import com.ruipengkj.service.TUserService;
import com.ruipengkj.view.base.BasePanel;

/**
 * 说明： 下单面板-底部信息区
 */
public class OrderDishBottom extends BasePanel implements QueryMember {

	private static final long serialVersionUID = 1L;

	private JButton orderButton;// 下单
	private JButton deskButton;// 换桌
	private JButton billButton;// 埋单
	private JButton hungButton;// 挂单
	private JButton obtainButon;// 取单
	private JButton cancleButton;// 撤单
	private JButton discountButon;// 整单折
	private JButton momeyButon;// 钱箱
	private JButton salesaviorderButon;//合单
	private JButton removeorderButon;//拆单
	private JLabel shouldLabel;// 应收
	private JLabel discountLabel;// 整单折扣
	private JLabel actualLabel;// 实收
	private JLabel favourableLabel;// 优惠

	private JLabel nameLabel;// 会员名称
	private JLabel mobileLabel;// 手机号
	private JLabel expendLabel;// 消费次数
	private JLabel cardNumLabel;// 卡号
	private JLabel scoresLabel;// 积分
	private JLabel moneyLabel;// 储值

	private OrderAddPanel orderAddPanel;
	private OrderRemove orderRemove;
	
	private TUser tUser = null;// 会员
	// 会员
	private TUserService tUserService = BuildSpringApplication.getInstance()
			.getTUserServiceImpl();// 会员
	// 配置信息
	private TConfigService tConfigService = BuildSpringApplication
			.getInstance().getTConfigServiceImpl();

	public OrderDishBottom() {
		this.setLayout(new BorderLayout());
		this.add(uiFactory.createFlowJPanel(), BorderLayout.NORTH);
		this.add(uiFactory.createFlowJPanel(), BorderLayout.SOUTH);
		this.add(uiFactory.createFlowJPanel(), BorderLayout.EAST);
		this.add(uiFactory.createFlowJPanel(), BorderLayout.WEST);
		this.add(initBottom());
		this.setOpaque(false);
		initThread();
		cardNumLabel.addComponentListener(new CardComponentListener());
	}

	//
	public void initThread() {
		ApplicationContext.listenCard(cardNumLabel,
				ApplicationContext.CardType.CT_DLSended);
		ApplicationContext.query_member = this;
	}

	// 初始化底部
	private JPanel initBottom() {
		JPanel bottomPanel = new RPJPanelOrderDispose();
		Util.setSize(bottomPanel, 1167, 94);

		orderButton = createJButto("下单", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_OBTAIN), 0);// 下单
		deskButton = createJButto("换桌", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_HUNG), 0);// 换桌
		billButton = createJButto("结账", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_BILL), 1);// 埋单
		hungButton = createJButto("挂单", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_HUNG), 0);// 挂单
		obtainButon = createJButto("取单", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_OBTAIN), 0);// 取单
		cancleButton = createJButto("撤单", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_CANCLE), 0);// 撤单
		discountButon = createJButto("整单折", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_DISCOUNT), 0);// 整单折
		momeyButon = createJButto("钱箱", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_MONEY), -1);// 钱箱
		salesaviorderButon = createJButto("合单", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_OBTAIN), 0);//销售合单
		removeorderButon = createJButto("拆单", 80, 34,
				ImageFactory.loadImage(ImageFactory.BTN_ORDER_OBTAIN), 0);//销售拆单
		JPanel jp3 = new JPanelFlowLayoutComponent(new Component[] {
				uiFactory.createJLabel("        ", false), billButton,
				orderButton, deskButton, // 下单，换桌
				// hungButton, obtainButon,
				cancleButton, salesaviorderButon,removeorderButon,discountButon, momeyButon }, FlowLayout.LEFT);
		jp3.setLayout(new FlowLayout(FlowLayout.LEFT, -6, 0));

		Color labelColor = new Color(234, 99, 0);
		shouldLabel = uiFactory.createJLabel("0.0", labelColor, JLabel.LEFT);// 应收
		discountLabel = uiFactory.createJLabel("1.0", labelColor, JLabel.LEFT);// 整单折扣
		actualLabel = uiFactory.createJLabel("0.0", labelColor, JLabel.LEFT);// 实收
		favourableLabel = uiFactory
				.createJLabel("0.0", labelColor, JLabel.LEFT);// 优惠
		JPanel jp4 = new JPanelFlowLayoutComponent(
				new Component[] {
						uiFactory.createJLabel("        应收：", labelColor,
								JLabel.RIGHT),
						shouldLabel,
						uiFactory.createJLabel("     整单折扣：", labelColor,
								JLabel.RIGHT),
						discountLabel,
						uiFactory.createJLabel("         实收：", labelColor,
								JLabel.RIGHT),
						actualLabel,
						uiFactory.createJLabel("         优惠：", labelColor,
								JLabel.RIGHT), favourableLabel },
				FlowLayout.LEFT);

		// 左边 应收款，折扣，挂起，结账等的面板
		JPanel jp2 = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		JPanel jp10 = uiFactory.createFlowJPanel();
		Util.setSize(jp10, 7, 7);
		jp2.add(jp10);
		jp2.add(jp4);
		jp2.add(jp3);
		jp2.setOpaque(false);

		nameLabel = new JLabel("", JLabel.LEFT);// 会员名称
		mobileLabel = new JLabel("", JLabel.LEFT);// 手机号
		expendLabel = new JLabel("", JLabel.LEFT);// 消费次数
		cardNumLabel = new JLabel("", JLabel.LEFT);// 卡号
		scoresLabel = new JLabel("", JLabel.LEFT);// 积分
		moneyLabel = new JLabel("", JLabel.LEFT);// 储值

		JPanel jp = new JPanelGridLayoutComponent(new Component[] {
				new JLabel("会员名称：", JLabel.RIGHT), nameLabel,
				new JLabel("手机号：", JLabel.RIGHT), mobileLabel,
				new JLabel("消费次数：", JLabel.RIGHT), expendLabel,
				new JLabel("卡号：", JLabel.RIGHT), cardNumLabel,
				new JLabel("积分：", JLabel.RIGHT), scoresLabel,
				new JLabel("储值：", JLabel.RIGHT), moneyLabel }, 2, 6);
		jp.setOpaque(false);

		BoxLayout boxLayout = new BoxLayout(bottomPanel, BoxLayout.X_AXIS);
		bottomPanel.setLayout(boxLayout);
		bottomPanel.add(jp2);
		bottomPanel.add(jp);

		return bottomPanel;
	}

	private JButton createJButto(String text, int width, int height,
			ImageIcon icon, int type) {
		JButton jb = new RPJButtonOrderDispose(text, icon, type);// text显示文本
		Util.setSize(jb, width, height);// 宽、高
		jb.addActionListener(this);// 添加监听器
		return jb;
	}

	// 统计总价格
	public void totalPrice(TCommodity commodity, int andOrSub) {
		if (commodity != null) {

			shouldLabel.setText(Util.DoubleHowMany(
					1,
					Double.parseDouble(shouldLabel.getText())
							+ commodity.getDiscountPrice() * andOrSub)
					+ "");
			actualLabel.setText(Util.DoubleHowMany(
					1,
					Double.parseDouble(shouldLabel.getText())
							* Double.parseDouble(discountLabel.getText()))
					+ "");
			favourableLabel.setText(Util.DoubleHowMany(
					1,
					Double.parseDouble(shouldLabel.getText())
							- Double.parseDouble(actualLabel.getText()))
					+ "");
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == orderButton) {// 下单
			if (orderAddPanel.BillAction(shouldLabel.getText(), discountLabel.getText(), 2))
				clear();
		} else if (e.getSource() == deskButton) {// 换桌
			if (orderAddPanel.getTableRow() <= 0
					|| orderAddPanel.getOrder() == null) {
				Util.showMessageDialog("尚未下单，无需换桌！");
				return;
			}
			OrderDeskReplace OrderDeskReplace = new OrderDeskReplace(1);
			OrderDeskReplace.showDialog(orderAddPanel.getOrder());
			if (OrderDeskReplace.isSuccess) {
				orderAddPanel.saveOrder(null);
			}
		} else if (e.getSource() == billButton) {// 结账
			orderAddPanel.settUser(tUser);
			if (orderAddPanel.BillAction(shouldLabel.getText(), discountLabel.getText(), 1))
				clear();
		} else if (e.getSource() == hungButton) {// 挂单
			orderAddPanel.hungAction(discountLabel.getText(),
					(RPJButtonOrderDispose) obtainButon);
		} else if (e.getSource() == obtainButon) {// 取单
			orderAddPanel.obtainAction(discountLabel, shouldLabel, actualLabel,
					favourableLabel, obtainButon);
		} else if (e.getSource() == discountButon) {// 整单折
			OrderDiscounDialog OrderDiscounDialog = new OrderDiscounDialog();
			if (OrderDiscounDialog.isSuccess) {
				discountLabel.setText(OrderDiscounDialog.getText());
				actualLabel.setText(Util.DoubleHowMany(
						1,
						Double.parseDouble(shouldLabel.getText())
								* Double.parseDouble(discountLabel.getText()))
						+ "");

				favourableLabel.setText(Util.DoubleHowMany(
						1,
						Double.parseDouble(shouldLabel.getText())
								- Double.parseDouble(actualLabel.getText()))
						+ "");
				// Util.showMessageDialog("更改成功！");
				billButton.doClick();
			}
		} else if (e.getSource() == cancleButton) {
			if (Util.showConfirmDialog("撤单将删除订单，确定撤单吗？") == 0) {
				orderAddPanel.delOrder();
				clear();
				orderAddPanel.clean();
			}
		} else if (e.getSource() == momeyButon) {// 钱箱
			// 打印
			List<TConfig> configList;
			try {
				configList = tConfigService.findService(null);

				if (configList == null || configList.size() == 0) {
					JOptionPane.showMessageDialog(null, "打印失败，请先到系统设置配置打印机");
					return;
				}
				TConfig config = configList.get(0);
				if (config.getSmallPrintName() == null) {
					JOptionPane.showMessageDialog(null, "打印失败，请先到系统设置配置打印机");
					return;
				} else if (config.getSmallPrintName().equals("")) {
					return;// 不打印时
				}
				new CashboxPrint(config.getSmallPrintName()).start();
			} catch (Exception e1) {
				e1.printStackTrace();
			}

			// try {
			// CommPortIdentifier portID =
			// CommPortIdentifier.getPortIdentifier("LPT1");
			// // 打开打印机端口
			// ParallelPort port = (ParallelPort) portID.open("Read", 30);
			// port.addEventListener(new ParallelPortEventListener() {
			// @Override
			// public void parallelEvent(ParallelPortEvent e) {
			// System.out.println(e.toString());
			// }
			// });
			//
			// OutputStream out = port.getOutputStream();
			// out.write(new byte[] { 0x1D, 0X61, 0x0F });
			//
			// InputStream in = port.getInputStream();
			// System.out.println(in.read());
			// // 关闭打印机端口
			// port.close();
			// } catch (Exception e2) {
			// e2.printStackTrace();
			// }

			// send("9b3ccd8e");
			// String os = System.getProperty("os.name");
			// if (os.contains("Windows")) {
			// // Windows
			// try {
			// FileWriter fw = new FileWriter("LPT1:T58N");
			// if (fw != null) {
			// PrintWriter pw = new PrintWriter(fw);
			// // 普通打印
			// pw.write("English-Windows" + "\n");
			// pw.write("中文-Windows" + "\n");
			// // 打印机开钱箱指令
			// char[] c = { 27, 'p', 0, 60, 240 };
			// pw.write(c);
			// pw.write("\n");
			// pw.flush();
			// // System.out.println("aaaaa");
			// }
			// } catch (FileNotFoundException ex) {
			// // Logger.getLogger(PrintTest.class.getName()).log(Level.SEVERE,
			// // null, ex);
			// ex.printStackTrace();
			// } catch (IOException e2) {
			// e2.printStackTrace();
			// }
			// } else {
			// // Linux
			// try {
			// FileOutputStream fos = new FileOutputStream("/dev/lp0");
			// // 普通打印
			// fos.write("English-Linux\n".getBytes());
			// fos.write("中文-Linux\n".getBytes("GBK"));
			// // 打印机开钱箱指令
			// char[] c = { 27, 'p', 0, 60, 240 };
			// for (int i = 0; i < c.length; i++) {
			// fos.write(c[i]);
			// }
			// fos.write("\n".getBytes());
			// fos.flush();
			// } catch (IOException ex) {
			// // Logger.getLogger(PrintTest.class.getName()).log(Level.SEVERE,
			// // null, ex);
			// ex.printStackTrace();
			// }
			// }
		}
		else if (e.getSource() == salesaviorderButon) {
			OrderAvi orderavi =  new OrderAvi((JDialog)null,"销售合单",true);
			orderavi.setVisible(true);
		}
		else if (e.getSource() == removeorderButon) {
			TOrder order = orderAddPanel.getOrder();
			if (order == null || order.getOrderID() == null || order.getOrderID().equals("")) {
				Util.showMessageDialog("请先选择需要拆分的订单！");
				return;
			}
			OrderRemove orderRemove =  new OrderRemove((JDialog)null,"销售拆单",true, order.getOrderID());
			orderRemove.setVisible(true);
		}
	}

	// 打印
	public void printOrder(List<TCommodity> commodityList, TOrder tOrder, TExePos tExePos) {
		// 打印
		try {
			List<TConfig> configList = tConfigService.findService(null);
			if (configList == null || configList.size() == 0) {
				JOptionPane.showMessageDialog(null, "打印失败，请先到系统设置配置打印机");
				return;
			}
			TConfig config = configList.get(0);
			if (config.getSmallPrintName() == null) {
				JOptionPane.showMessageDialog(null, "打印失败，请先到系统设置配置打印机");
				return;
			} else if (config.getSmallPrintName().equals("")) {
				return;// 不打印时
			}
			if (tUser != null && tUser.getUserID() != null)
				new TicketPrint(tExePos, tOrder, commodityList,
						config.getSmallPrintName(), true).start();
			else
				new TicketPrint(tExePos, tOrder, commodityList,
						config.getSmallPrintName(), false).start();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	//信息统计，查看
	public void Message() {
		
	}
	
	// 查看会员信息
	private void lookMember() {
		try {
			String carID = cardNumLabel.getText().trim();
			if (carID.length() > 15) {
				JOptionPane.showMessageDialog(null, "会员编号不能超过15个字");
				return;
			}
			if (!carID.equals("")) {
				tUser = tUserService.getByCardNumService(carID);
			} else {
				return;
			}
			if (tUser != null) {
				mobileLabel.setText(tUser.getMobile());
				scoresLabel.setText(tUser.getPoint() + "");
				nameLabel.setText(tUser.getRealName());
				moneyLabel.setText(tUser.getMoney() + "");
				expendLabel.setText(tUser.getBuyCount() + "");
				return;
			}
			cardNumLabel.setText("");
			Util.showMessageDialog("非法会员！");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void queryMember() {
		lookMember();
	}

	public OrderAddPanel getOrderAddPanel() {
		return orderAddPanel;
	}

	public void setOrderAddPanel(OrderAddPanel orderAddPanel) {
		this.orderAddPanel = orderAddPanel;
	}

	@Override
	public void clear() {
		// 清除价格
		shouldLabel.setText("0.0");// 应收
		discountLabel.setText("1.0");// 整单折扣
		actualLabel.setText("0.0");// 实收
		favourableLabel.setText("0.0");// 优惠
		// 清除会员
		nameLabel.setText("");// 会员名称
		mobileLabel.setText("");// 手机号
		expendLabel.setText("");// 消费次数
		cardNumLabel.setText("");// 卡号
		scoresLabel.setText("");// 积分
		moneyLabel.setText("");// 储值

		tUser = null;
//		cardNumLabel.setText("1");
//		queryMember();
	}

}
